import 'package:flutter/material.dart';
import 'dart:io';
import '../models/exam_model.dart';
import '../models/question_model.dart';
import '../utils/responsive_util.dart';
import 'home_screen.dart';
import 'answer_details_screen.dart';
import 'dart:async'; // 导入Timer
import '../data/user_data.dart'; // 导入UserData
import 'package:intl/intl.dart'; // 导入intl库
import '../services/image_service.dart'; // 导入图片服务
import '../services/exam_service.dart'; // 导入考试服务
import '../services/exam_state_service.dart';
import 'package:flutter/services.dart';

class ResultScreen extends StatefulWidget {
  final Exam exam;
  final ExamResult result;
  final bool fromCompletedExam; // 是否从已完成考试进入

  const ResultScreen({
    super.key,
    required this.exam,
    required this.result,
    this.fromCompletedExam = false, // 默认为false
  });

  @override
  State<ResultScreen> createState() => _ResultScreenState();
}

class _ResultScreenState extends State<ResultScreen> {
  late int _totalObjectiveQuestions;
  late int _totalSubjectiveQuestions;
  late int _totalFillBlankQuestions;
  late int _totalShortAnswerQuestions;
  late int _correctObjectiveQuestions;
  // 控制查看答案按钮的可见性
  bool _showViewAnswersButton = false; // 初始设为false，暂时屏蔽该功能
  final int _tapCount = 0; // 添加一个静态变量来存储点击次数
  
  // 自动登出相关变量
  Timer? _logoutTimer;
  int _remainingSeconds = 30; // 倒计时30秒
  bool _showCountdown = true; // 是否显示倒计时
  
  // 添加变量存储当前选中的问题
  Question? _selectedQuestion;
  // 存储更新后的结果
  late ExamResult _updatedResult;
  bool _isExporting = false;
  String? _exportedFilePath;
  String? _exportedZipPath;

  @override
  void initState() {
    super.initState();
    _calculateQuestionCounts();
    // 只有在不是从已完成考试进入时才启动倒计时
    if (!widget.fromCompletedExam) {
      _startLogoutTimer(); // 启动倒计时
    } else {
      _showCountdown = false; // 从已完成考试进入时不显示倒计时
    }
    _updatedResult = widget.result;
  }
  
  @override
  void dispose() {
    _logoutTimer?.cancel(); // 取消定时器
    super.dispose();
  }
  
  // 启动自动登出倒计时
  void _startLogoutTimer() {
    _logoutTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_remainingSeconds > 0) {
          _remainingSeconds--;
        } else {
          _logoutTimer?.cancel();
          _logout(); // 时间结束自动登出
        }
      });
    });
  }
  
  // 登出操作
  void _logout() {
    UserData.logout(); // 登出当前用户
    Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => false); // 跳转到登录页面并清除路由栈
  }

  void _calculateQuestionCounts() {
    _totalObjectiveQuestions = widget.exam.questions.where((q) =>
      q.type != QuestionType.shortAnswer && q.type != QuestionType.fillBlank
    ).length;

    _totalSubjectiveQuestions = widget.exam.questions.where((q) =>
      q.type == QuestionType.shortAnswer
    ).length;

    _totalFillBlankQuestions = widget.exam.questions.where((q) =>
      q.type == QuestionType.fillBlank
    ).length;

    _totalShortAnswerQuestions = widget.exam.questions.where((q) =>
      q.type == QuestionType.shortAnswer
    ).length;

    // 计算客观题正确的数量
    _correctObjectiveQuestions = _calculateCorrectObjectiveQuestions();
  }

  // 计算正确的客观题数量
  int _calculateCorrectObjectiveQuestions() {
    // 获取所有客观题（排除填空题和简答题）
    final objectiveQuestions = widget.exam.questions.where((q) =>
      q.type != QuestionType.shortAnswer && q.type != QuestionType.fillBlank
    ).toList();

    // 计算正确的客观题数量
    int correctCount = 0;

    for (var question in objectiveQuestions) {
      final userAnswer = widget.result.answers[question.id];

      if (userAnswer != null) {
        bool isCorrect = false;

        // 根据题目类型检查答案是否正确
        if (question is SingleChoiceQuestion) {
          if (question.correctOption >= 0 && question.correctOption < question.choices.length) {
            final correctChoiceId = question.choices[question.correctOption].id;
            // 确保用户答案是字符串类型
            final userAnswerStr = userAnswer.toString();
            isCorrect = userAnswerStr == correctChoiceId;
          }
        } else if (question is MultipleChoiceQuestion) {
          // 获取正确选项ID列表
          List<String> correctChoiceIds = [];
          for (int index in question.correctOptions) {
            if (index >= 0 && index < question.choices.length) {
              correctChoiceIds.add(question.choices[index].id);
            }
          }

          // 检查用户答案是否完全正确
          if (userAnswer is List) {
            final userAnswerList = userAnswer.cast<String>();
            if (userAnswerList.length == correctChoiceIds.length &&
                userAnswerList.every((option) => correctChoiceIds.contains(option)) &&
                correctChoiceIds.every((option) => userAnswerList.contains(option))) {
              isCorrect = true;
            }
          }
        } else if (question is TrueOrFalseQuestion) {
          // 判断题答案可能是布尔值或字符串
          bool correctAnswer = question.correctAnswer;
          if (userAnswer is bool) {
            isCorrect = userAnswer == correctAnswer;
          } else if (userAnswer is String) {
            // 字符串转布尔值
            bool userBoolAnswer = userAnswer.toLowerCase() == 'true';
            isCorrect = userBoolAnswer == correctAnswer;
          }
        }

        if (isCorrect) {
          correctCount++;
        }
      }
    }

    return correctCount;
  }

  // 切换查看答案按钮的可见性
  void _toggleViewAnswersButton() {
    setState(() {
      _showViewAnswersButton = !_showViewAnswersButton;
    });
  }

  // 获取问题对应的照片列表
  List<String> _getQuestionPhotos(String questionId) {
    return _updatedResult.answerImages[questionId] ?? [];
  }
  
  // 拍照并添加到答题照片
  Future<void> _takePhoto(String questionId) async {
    final File? photo = await ImageService.takePhoto();
    if (photo != null) {
    setState(() {
        _updatedResult = _updatedResult.addAnswerImage(questionId, photo.path);
      });
      _saveUpdatedResult();
    }
  }
  
  // 从相册选择图片并添加到答题照片
  Future<void> _pickImage(String questionId) async {
    // 禁用从相册选择图片功能
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Text('考试中只允许拍照上传，不允许从相册选择图片'),
        backgroundColor: Colors.red.shade600,
      ),
    );
    return;
    
    /* 以下代码已禁用
    final File? image = await ImageService.pickImageFromGallery();
    if (image != null) {
      setState(() {
        _updatedResult = _updatedResult.addAnswerImage(questionId, image.path);
      });
      _saveUpdatedResult();
    }
    */
  }
  
  // 删除答题照片
  void _removeAnswerImage(String questionId, String imagePath) {
    setState(() {
      _updatedResult = _updatedResult.removeAnswerImage(questionId, imagePath);
    });
    
    // 删除文件
    ImageService.deleteImage(imagePath);
    _saveUpdatedResult();
  }
  
  // 保存更新后的考试结果
  Future<void> _saveUpdatedResult() async {
    // 保存更新后的考试结果
    await ExamService.updateExamResult(_updatedResult);
    
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('照片已保存'),
        duration: Duration(seconds: 2),
        backgroundColor: Colors.green,
      ),
    );
  }
  
  // 显示选择题目对话框
  void _showQuestionSelectionDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('选择要添加照片的题目'),
          content: SizedBox(
            width: double.maxFinite,
            height: MediaQuery.of(context).size.height * 0.6,
            child: ListView.builder(
              itemCount: widget.exam.questions.length,
              itemBuilder: (context, index) {
                Question question = widget.exam.questions[index];
                return ListTile(
                  title: Text('题目 ${index + 1}', 
                    style: const TextStyle(fontWeight: FontWeight.bold)),
                  subtitle: Text(
                    question.text.length > 50 
                      ? '${question.text.substring(0, 50)}...' 
                      : question.text
                  ),
                  trailing: _getQuestionPhotos(question.id).isNotEmpty 
                    ? Badge(
                        label: Text('${_getQuestionPhotos(question.id).length}'),
                        child: const Icon(Icons.photo_library),
                      )
                    : null,
                  onTap: () {
                    Navigator.pop(context);
                    setState(() {
                      _selectedQuestion = question;
                    });
                    _showPhotoUploadDialog(question);
                  },
                );
              },
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
          ],
        );
      },
    );
  }
  
  // 显示照片上传对话框
  void _showPhotoUploadDialog(Question question) {
    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            List<String> answerImages = _getQuestionPhotos(question.id);
            
            return AlertDialog(
              title: const Text('为题目添加照片'),
              content: SizedBox(
                width: double.maxFinite,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(question.text, 
                      style: const TextStyle(fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        ElevatedButton.icon(
                          onPressed: () async {
                            Navigator.pop(context);
                            await _takePhoto(question.id);
                            _showPhotoUploadDialog(question);
                          },
                          icon: const Icon(Icons.camera_alt),
                          label: const Text('拍照'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue.shade600,
                          ),
                        ),
                        ElevatedButton.icon(
                          onPressed: () async {
                            Navigator.pop(context);
                            await _pickImage(question.id);
                            _showPhotoUploadDialog(question);
                          },
                          icon: const Icon(Icons.photo_library),
                          label: const Text('相册'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green.shade600,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    if (answerImages.isNotEmpty) ...[
                      const Text('已添加的照片：', 
                        style: TextStyle(fontWeight: FontWeight.bold)),
                      const SizedBox(height: 8),
                      SizedBox(
                        height: 200,
                        child: GridView.builder(
                          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            crossAxisSpacing: 8,
                            mainAxisSpacing: 8,
                          ),
                          itemCount: answerImages.length,
                          itemBuilder: (context, index) {
                            return Stack(
                              children: [
                                Container(
                                  decoration: BoxDecoration(
                                    border: Border.all(color: Colors.grey.shade300),
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(8),
                                    child: Image.file(
                                      File(answerImages[index]),
                                      fit: BoxFit.cover,
                                      width: double.infinity,
                                      height: double.infinity,
                                    ),
                                  ),
                                ),
                                Positioned(
                                  top: 4,
                                  right: 4,
                                  child: InkWell(
                                    onTap: () {
                                      Navigator.pop(context);
                                      _removeAnswerImage(question.id, answerImages[index]);
                                      _showPhotoUploadDialog(question);
                                    },
                                    child: Container(
                                      padding: const EdgeInsets.all(4),
                                      decoration: BoxDecoration(
                                        color: Colors.red.withOpacity(0.7),
                                        shape: BoxShape.circle,
                                      ),
                                      child: const Icon(
                                        Icons.close,
                                        size: 16,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            );
                          },
                        ),
                      ),
                    ],
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('完成'),
                ),
              ],
            );
          }
        );
      },
    );
  }

  // 导出考试结果为Excel文件
  Future<void> _exportResult() async {
    setState(() {
      _isExporting = true;
    });
    
    try {
      // 计算考试用时（分钟）
      final examDurationInMinutes = widget.exam.duration;

      // 尝试从考试结果的提交时间推算实际用时，如果无法获取则使用总时长
      int usedTimeInMinutes = examDurationInMinutes; // 默认使用总时长

      // 如果有提交时间，可以尝试推算实际用时
      // 注意：这里只是一个估算，实际用时应该在考试提交时记录
      if (_updatedResult.submittedAt != null) {
        // 这里可以添加更精确的用时计算逻辑
        // 目前暂时使用总时长作为占位符
        usedTimeInMinutes = examDurationInMinutes;
      }
      
      final filePath = await ExamStateService.exportExamResultToExcel(
        _updatedResult, 
        widget.exam,
        usedTimeInMinutes
      );
      
      setState(() {
        _isExporting = false;
        _exportedFilePath = filePath;
      });
      
      if (filePath != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('考试结果已导出到: $filePath'),
            duration: const Duration(seconds: 3),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('导出失败，请重试'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      setState(() {
        _isExporting = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('导出错误: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
  
  // 打包考试结果和照片为ZIP文件
  Future<void> _packageResultToZip() async {
    setState(() {
      _isExporting = true;
    });
    
    try {
      // 计算考试用时（分钟）
      final examDurationInMinutes = widget.exam.duration;

      // 尝试从考试结果的提交时间推算实际用时，如果无法获取则使用总时长
      int usedTimeInMinutes = examDurationInMinutes; // 默认使用总时长

      // 如果有提交时间，可以尝试推算实际用时
      // 注意：这里只是一个估算，实际用时应该在考试提交时记录
      if (_updatedResult.submittedAt != null) {
        // 这里可以添加更精确的用时计算逻辑
        // 目前暂时使用总时长作为占位符
        usedTimeInMinutes = examDurationInMinutes;
      }
      
      // 检查是否已有导出的Excel文件
      final String? excelPath = _exportedFilePath;
      
      final zipPath = await ExamStateService.packageExamResultsToZip(
        _updatedResult, 
        widget.exam,
        usedTimeInMinutes,
        excelPath ?? ''
      );
      
      setState(() {
        _isExporting = false;
        _exportedZipPath = zipPath;
      });
      
      if (zipPath != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('考试结果和照片已打包为ZIP文件: $zipPath'),
            duration: const Duration(seconds: 3),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('打包失败，请重试'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      setState(() {
        _isExporting = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('打包错误: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    final double standardSpacing = ResponsiveUtil.getSpacing(context, 16.0);
    final double largeSpacing = ResponsiveUtil.getSpacing(context, 24.0);
    final double buttonMinWidth = ResponsiveUtil.getButtonMinWidth(context);
    
    return WillPopScope(
      onWillPop: () async {
        // 拦截用户的返回操作，显示确认对话框
        final bool? shouldPop = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('确认返回?'),
            content: const Text('确定要返回首页吗?'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false), // 不离开
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop(true); // 确认离开
                  _navigateToHome();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                ),
                child: const Text('返回首页'),
              ),
            ],
          ),
        );
        return false; // 始终阻止默认返回行为，使用自定义导航
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            '考试结果',
            style: ResponsiveUtil.getBalancedTextStyle(
              context,
              fontSize: ResponsiveUtil.isTablet(context) ? 22 : 20,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          backgroundColor: Colors.blue.shade800,
          foregroundColor: Colors.white,
          toolbarHeight: ResponsiveUtil.scaleHeight(context, 60.0),
          automaticallyImplyLeading: widget.fromCompletedExam, // 从已完成考试进入时显示返回按钮
          leading: widget.fromCompletedExam
            ? IconButton(
                icon: const Icon(Icons.arrow_back, color: Colors.white),
                onPressed: () => Navigator.pop(context),
                tooltip: '返回',
              )
            : null,
          actions: [
            // 显示自动登出倒计时
            if (_showCountdown)
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                    margin: const EdgeInsets.only(right: 16),
                    decoration: BoxDecoration(
                      color: _remainingSeconds <= 10 ? Colors.red.shade700 : Colors.blue.shade700,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Row(
                      children: [
                        const Icon(Icons.timer, size: 16),
                        const SizedBox(width: 4),
                        Text(
                          "$_remainingSeconds秒后自动登出",
                          style: const TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
              ),
          ],
        ),
        body: SingleChildScrollView(
          padding: EdgeInsets.all(standardSpacing),
          child: Center(
            child: ConstrainedBox(
              constraints: BoxConstraints(
                maxWidth: ResponsiveUtil.getContentMaxWidth(context),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (widget.result.avatarPath != null && widget.result.avatarPath!.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Row(
                        children: [
                          CircleAvatar(
                            radius: 36,
                            backgroundImage: FileImage(File(widget.result.avatarPath!)),
                          ),
                          const SizedBox(width: 16),
                          const Text('本次考试头像', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                        ],
                      ),
                    ),
                  // 顶部结果卡片
                  _buildResultCard(),
                  SizedBox(height: largeSpacing),
                  
                  // 题型作答详情
                  _buildAnsweredQuestionsDetail(),
                  SizedBox(height: largeSpacing),
                  
                  // 客观题答题数量
                  _buildObjectiveAnsweredCountCard(),
                  
                  SizedBox(height: largeSpacing),
                  
                  // 按钮区域 - 使用Wrap而不是单行放置按钮，避免按钮挤压
                  Wrap(
                    spacing: standardSpacing,
                    runSpacing: standardSpacing,
                    alignment: WrapAlignment.center,
                    children: [
                      // 查看详情按钮 - 仅在_showViewAnswersButton为true时显示
                      if (_showViewAnswersButton)
                        SizedBox(
                          width: isTablet ? ResponsiveUtil.scaleWidth(context, 200) : double.infinity,
                          height: ResponsiveUtil.getButtonMinHeight(context),
                          child: OutlinedButton.icon(
                            onPressed: () {
                              // 导航到详细答案页面
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => AnswerDetailsScreen(
                                    exam: widget.exam,
                                    result: _updatedResult,
                                  ),
                                  settings: const RouteSettings(name: 'AnswerDetailsScreen'),
                                ),
                              );
                            },
                            icon: Icon(Icons.article, size: ResponsiveUtil.getIconSize(context, base: 20)),
                            label: Text(
                              '查看详细答案',
                              textAlign: TextAlign.center,
                              style: ResponsiveUtil.getBalancedTextStyle(
                                context,
                                fontSize: ResponsiveUtil.isTablet(context) ? 18 : 16,
                                fontWeight: FontWeight.bold,
                                color: Colors.blue.shade800,
                                overflow: TextOverflow.visible,
                              ),
                            ),
                            style: OutlinedButton.styleFrom(
                              foregroundColor: Colors.blue.shade800,
                              side: BorderSide(color: Colors.blue.shade800),
                              padding: EdgeInsets.symmetric(
                                horizontal: ResponsiveUtil.getButtonHorizontalPadding(context),
                                vertical: ResponsiveUtil.scaleHeight(context, 16),
                              ),
                              minimumSize: Size(
                                ResponsiveUtil.getButtonMinWidth(context), 
                                ResponsiveUtil.getButtonMinHeight(context)
                              ),
                              textStyle: ResponsiveUtil.getBalancedTextStyle(
                                context,
                                fontSize: ResponsiveUtil.isTablet(context) ? 18 : 16,
                                fontWeight: FontWeight.bold,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(
                                  ResponsiveUtil.getBorderRadius(context)
                                ),
                              ),
                              alignment: Alignment.center,
                            ),
                          ),
                        ),
                      
                      // 当查看答案功能被禁用时显示的提示文字
                      if (!_showViewAnswersButton)
                        Padding(
                          padding: EdgeInsets.symmetric(vertical: standardSpacing),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.info_outline,
                                size: ResponsiveUtil.getIconSize(context, base: 16),
                                color: Colors.grey.shade600,
                              ),
                              const SizedBox(width: 8),
                              Text(
                                "查看答案功能暂时不可用",
                                style: ResponsiveUtil.getBalancedTextStyle(
                                  context,
                                  fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                                  color: Colors.grey.shade600,
                                ),
                              ),
                            ],
                          ),
                        ),
                    ],
                  ),
                  SizedBox(height: standardSpacing),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  void _navigateToHome() {
    // 取消自动登出计时器
    _logoutTimer?.cancel();

    Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(
        builder: (context) => const HomeScreen(skipIncompleteExamCheck: true), // 跳过未完成考试检查
        settings: const RouteSettings(name: 'HomeScreen')
      ),
      (route) => false, // 清除路由栈
    );
  }

  Widget _buildResultCard() {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    final double standardSpacing = ResponsiveUtil.getSpacing(context, 16.0);
    
    return Card(
      elevation: 3,
      margin: EdgeInsets.only(bottom: standardSpacing),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(
          ResponsiveUtil.getBorderRadius(context, base: 12)
          ),
        side: BorderSide(color: Colors.blue.shade100),
        ),
        child: Padding(
        padding: EdgeInsets.all(standardSpacing),
          child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
            children: [
            // 考试标题
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Icon(Icons.assignment_turned_in, color: Colors.blue.shade800, size: ResponsiveUtil.getIconSize(context)),
                SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                Expanded(
                  child: Text(
                    widget.exam.title,
                    style: ResponsiveUtil.getBalancedTextStyle(
                      context,
                      fontSize: ResponsiveUtil.isTablet(context) ? 24 : 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
            
            Divider(height: ResponsiveUtil.scaleHeight(context, 24), thickness: 1, color: Colors.grey.shade200),
            
            // 完成状态
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                        '考试已完成',
                          style: ResponsiveUtil.getBalancedTextStyle(
                            context,
                          fontSize: ResponsiveUtil.isTablet(context) ? 20 : 18,
                            fontWeight: FontWeight.bold,
                          color: Colors.green.shade700,
                          ),
                        ),
                      SizedBox(height: ResponsiveUtil.scaleHeight(context, 4)),
                        Text(
                        '提交时间: ${widget.result.submittedAt != null ? DateFormat('yyyy-MM-dd HH:mm:ss').format(widget.result.submittedAt!) : "未知"}',
                          style: ResponsiveUtil.getBalancedTextStyle(
                            context,
                          fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                            color: Colors.grey.shade700,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.green.shade100,
                  ),
                  padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 8)),
                  child: Icon(
                    Icons.check,
                    color: Colors.green.shade700,
                    size: ResponsiveUtil.getIconSize(context, base: 24),
                    ),
                  ),
                ],
              ),
            
            SizedBox(height: ResponsiveUtil.scaleHeight(context, 16)),
            
            // 考试信息
              Row(
                children: [
                _buildInfoBox(
                  label: '总题目数',
                  value: '${widget.exam.questions.length}题',
                  icon: Icons.assignment,
                ),
                SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                _buildInfoBox(
                  label: '客观题',
                  value: '$_totalObjectiveQuestions题',
                  icon: Icons.check_box_outlined,
                    ),
                SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                _buildInfoBox(
                  label: '填空题',
                  value: '$_totalFillBlankQuestions题',
                  icon: Icons.edit_outlined,
                    ),
                SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                _buildInfoBox(
                  label: '简答题',
                  value: '$_totalShortAnswerQuestions题',
                  icon: Icons.edit_note,
                    ),
              ],
                  ),
                ],
              ),
      ),
    );
  }

  Widget _buildAnsweredQuestionsDetail() {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    final double standardSpacing = ResponsiveUtil.getSpacing(context, 16.0);
    
    // 获取各种题型的已回答题目数量
    int answeredSingleChoice = 0;
    int answeredMultiChoice = 0;
    int answeredJudgment = 0;
    int answeredSubjective = 0;
    int answeredFillBlank = 0;

    // 创建一个集合存储已回答的题目ID
    Set<String> answeredQuestionIds = {};

    // 添加有文字答案的题目
    for (var questionId in widget.result.answers.keys) {
      // 跳过内部字段（以下划线开头的字段）
      if (questionId.startsWith('_')) {
        continue;
      }

      final answer = widget.result.answers[questionId];
      if (answer != null) {
        // 找到对应的题目
        final question = widget.exam.questions.firstWhere(
          (q) => q.id == questionId,
          orElse: () => SingleChoiceQuestion(
            id: '',
            text: '',
            score: 0,
            choices: [],
            correctOption: -1,
          ),
        );

        if (question.id.isEmpty) continue;

        // 根据题目类型进行特殊处理
        bool shouldCount = false;

        if (question.type == QuestionType.fillBlank) {
          // 填空题特殊处理
          final fillBlankQuestion = question as FillBlankQuestion;

          if (fillBlankQuestion.isMultiBlank) {
            // 多空填空题：必须所有空都填写才算已答题
            if (answer is List) {
              final answers = answer.map((item) => item?.toString() ?? '').toList();
              int filledCount = answers.where((ans) => ans.trim().isNotEmpty).length;
              // 只有全部填写完成才算已答题
              shouldCount = filledCount == fillBlankQuestion.blankCount;
            }
          } else {
            // 单空填空题：检查答案是否非空
            if (answer is String) {
              shouldCount = answer.trim().isNotEmpty;
            }
          }
        } else {
          // 其他题型的处理
          if (answer is List) {
            // 对于多选题，确保选择了至少一个选项
            shouldCount = answer.isNotEmpty;
          } else if (answer is String) {
            // 对于文本答案，确保不是空字符串
            shouldCount = answer.trim().isNotEmpty;
          } else {
            // 其他类型（如布尔值）直接算作已答题
            shouldCount = true;
          }
        }

        if (shouldCount) {
          answeredQuestionIds.add(questionId);
        }
      }
    }

    // 添加有照片答案的题目
    for (var questionId in widget.result.answerImages.keys) {
      final images = widget.result.answerImages[questionId];
      if (images != null && images.isNotEmpty) {
        answeredQuestionIds.add(questionId);
      }
    }

    // 根据已回答的题目ID统计各题型数量
    for (var questionId in answeredQuestionIds) {
      final question = widget.exam.questions.firstWhere(
        (q) => q.id == questionId,
        orElse: () => SingleChoiceQuestion(
          id: '',
          text: '',
          score: 0,
          choices: [],
          correctOption: -1,
        ),
      );

      if (question.id.isEmpty) continue;

      switch (question.type) {
        case QuestionType.singleChoice:
          answeredSingleChoice++;
          break;
        case QuestionType.multipleChoice:
          answeredMultiChoice++;
          break;
        case QuestionType.trueOrFalse:
          answeredJudgment++;
          break;
        case QuestionType.shortAnswer:
          answeredSubjective++;
          break;
        case QuestionType.fillBlank:
          answeredFillBlank++; // 填空题单独统计
          break;
      }
    }
    
    // 计算各种题型的总数
    int totalSingleChoice = 0;
    int totalMultiChoice = 0;
    int totalJudgment = 0;
    int totalSubjective = 0;
    int totalFillBlank = 0;
    
    for (var question in widget.exam.questions) {
      switch (question.type) {
        case QuestionType.singleChoice:
          totalSingleChoice++;
          break;
        case QuestionType.multipleChoice:
          totalMultiChoice++;
          break;
        case QuestionType.trueOrFalse:
          totalJudgment++;
          break;
        case QuestionType.shortAnswer:
          totalSubjective++;
          break;
        case QuestionType.fillBlank:
          totalFillBlank++;
          break;
      }
    }
    
    return Card(
      elevation: 3,
      margin: EdgeInsets.only(bottom: standardSpacing),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(
          ResponsiveUtil.getBorderRadius(context, base: 12)
        ),
        side: BorderSide(color: Colors.blue.shade100),
      ),
      child: Padding(
        padding: EdgeInsets.all(standardSpacing),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
                children: [
                Icon(Icons.assessment, color: Colors.blue.shade800, size: ResponsiveUtil.getIconSize(context)),
                SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                  Text(
                  '作答情况',
                    style: ResponsiveUtil.getBalancedTextStyle(
                      context,
                    fontSize: ResponsiveUtil.isTablet(context) ? 22 : 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              
                SizedBox(height: ResponsiveUtil.scaleHeight(context, 16)),
            
            // 显示各种题型的作答情况
            if (totalSingleChoice > 0)
              _buildQuestionTypeProgressRow(
                icon: Icons.radio_button_checked,
                title: '单选题',
                answered: answeredSingleChoice,
                total: totalSingleChoice,
                color: Colors.blue,
              ),
            
            if (totalMultiChoice > 0)
              _buildQuestionTypeProgressRow(
                icon: Icons.check_box,
                title: '多选题',
                answered: answeredMultiChoice,
                total: totalMultiChoice,
                color: Colors.purple,
                  ),
            
            if (totalJudgment > 0)
              _buildQuestionTypeProgressRow(
                icon: Icons.rule,
                title: '判断题',
                answered: answeredJudgment,
                total: totalJudgment,
                color: Colors.orange,
              ),
            
            if (totalFillBlank > 0)
              _buildQuestionTypeProgressRow(
                icon: Icons.edit_outlined,
                title: '填空题',
                answered: answeredFillBlank,
                total: totalFillBlank,
                color: Colors.orange,
                      ),
            if (totalSubjective > 0)
              _buildQuestionTypeProgressRow(
                icon: Icons.edit_note,
                title: '简答题',
                answered: answeredSubjective,
                total: totalSubjective,
                color: Colors.green,
                      ),
                    ],
                  ),
                ),
    );
  }
  
  // 构建每种题型的进度条行
  Widget _buildQuestionTypeProgressRow({
    required IconData icon,
    required String title,
    required int answered,
    required int total,
    required MaterialColor color,
  }) {
    final double progress = total > 0 ? answered / total : 0;
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Padding(
      padding: EdgeInsets.only(bottom: ResponsiveUtil.scaleHeight(context, 12)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
          Row(
            children: [
              Icon(icon, color: color.shade800, size: ResponsiveUtil.getIconSize(context, base: 18)),
                      SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
              Text(
                title,
                          style: ResponsiveUtil.getBalancedTextStyle(
                            context,
                  fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
              const Spacer(),
              Text(
                '$answered / $total',
                style: ResponsiveUtil.getBalancedTextStyle(
                  context,
                  fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                  fontWeight: FontWeight.bold,
                  color: color.shade800,
                ),
              ),
            ],
          ),
          SizedBox(height: ResponsiveUtil.scaleHeight(context, 4)),
          // 进度条
          ClipRRect(
            borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context, base: 4)),
            child: LinearProgressIndicator(
              value: progress,
              backgroundColor: color.shade100,
              valueColor: AlwaysStoppedAnimation<Color>(color.shade500),
              minHeight: ResponsiveUtil.scaleHeight(context, isTablet ? 10 : 8),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildObjectiveAnsweredCountCard() {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    final double standardSpacing = ResponsiveUtil.getSpacing(context, 16.0);
    
    // 先统一计算客观题总分
    double objectiveTotalScore = 0;
    List<Question> objectiveQuestions = [];
    
    // 识别所有客观题并计算总分（排除填空题和简答题）
    for (var question in widget.exam.questions) {
      if (question.type != QuestionType.shortAnswer && question.type != QuestionType.fillBlank) {
        objectiveQuestions.add(question);
        objectiveTotalScore += question.score;
      }
    }
    
    // 计算学生客观题得分
    double objectiveEarnedScore = 0;

    // 方法1：优先使用 ExamResult 的 objectiveScore 字段
    if (widget.result.objectiveScore > 0) {
      objectiveEarnedScore = widget.result.objectiveScore.toDouble();
    }
    // 方法2：如果 objectiveScore 未设置，手动计算
    else {
      // 遍历所有客观题
      for (var question in objectiveQuestions) {
        // 获取用户答案
        final userAnswer = widget.result.answers[question.id];

        if (userAnswer != null) {
          bool isCorrect = false;

          // 根据题目类型检查答案是否正确
          if (question is SingleChoiceQuestion) {
            if (question.correctOption >= 0 && question.correctOption < question.choices.length) {
              final correctChoiceId = question.choices[question.correctOption].id;
              // 确保用户答案是字符串类型
              final userAnswerStr = userAnswer.toString();
              if (userAnswerStr == correctChoiceId) {
                isCorrect = true;
                objectiveEarnedScore += question.score;
              }
            }
          } else if (question is MultipleChoiceQuestion) {
            // 获取正确选项ID列表
            List<String> correctChoiceIds = [];
            for (int index in question.correctOptions) {
              if (index >= 0 && index < question.choices.length) {
                correctChoiceIds.add(question.choices[index].id);
              }
            }

            // 检查用户答案是否完全正确
            if (userAnswer is List) {
              final userAnswerList = userAnswer.cast<String>();
              if (userAnswerList.length == correctChoiceIds.length &&
                  userAnswerList.every((option) => correctChoiceIds.contains(option)) &&
                  correctChoiceIds.every((option) => userAnswerList.contains(option))) {
                isCorrect = true;
                objectiveEarnedScore += question.score;
              }
            }
          } else if (question is TrueOrFalseQuestion) {
            // 判断题答案可能是布尔值或字符串
            bool correctAnswer = question.correctAnswer;
            if (userAnswer is bool) {
              if (userAnswer == correctAnswer) {
                isCorrect = true;
                objectiveEarnedScore += question.score;
              }
            } else if (userAnswer is String) {
              // 字符串转布尔值
              bool userBoolAnswer = userAnswer.toLowerCase() == 'true';
              if (userBoolAnswer == correctAnswer) {
                isCorrect = true;
                objectiveEarnedScore += question.score;
              }
            }
          }
        }
      }
    }
    
    // 确保得分不超过总分
    objectiveEarnedScore = objectiveEarnedScore > objectiveTotalScore ? objectiveTotalScore : objectiveEarnedScore;
    
    return Card(
      elevation: 2,
      margin: EdgeInsets.only(bottom: standardSpacing),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(
          ResponsiveUtil.getBorderRadius(context, base: 12)
        ),
        side: BorderSide(color: Colors.grey.shade200),
      ),
      child: Padding(
        padding: EdgeInsets.all(standardSpacing),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.check_circle_outline, color: Colors.green.shade600, size: ResponsiveUtil.getIconSize(context)),
                SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                Text(
                  '客观题答对数量',
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                    fontSize: ResponsiveUtil.isTablet(context) ? 20 : 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            SizedBox(height: ResponsiveUtil.scaleHeight(context, 20)),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '$_correctObjectiveQuestions',
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                    fontSize: ResponsiveUtil.isTablet(context) ? 48 : 40,
                    fontWeight: FontWeight.bold,
                    color: Colors.green.shade700,
                  ),
                  ),
                Text(
                  ' / $_totalObjectiveQuestions',
                    style: ResponsiveUtil.getBalancedTextStyle(
                      context,
                    fontSize: ResponsiveUtil.isTablet(context) ? 26 : 22,
                      fontWeight: FontWeight.bold,
                    color: Colors.grey.shade600,
                    ),
                  ),
              ],
                ),
            
            // 新增：客观题分数显示
            SizedBox(height: ResponsiveUtil.scaleHeight(context, 16)),
            Divider(height: 1, thickness: 1, color: Colors.grey.shade200),
            SizedBox(height: ResponsiveUtil.scaleHeight(context, 16)),
            
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.score, color: Colors.blue.shade600, size: ResponsiveUtil.getIconSize(context)),
                SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                Text(
                  '客观题得分',
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                    fontSize: ResponsiveUtil.isTablet(context) ? 20 : 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            SizedBox(height: ResponsiveUtil.scaleHeight(context, 12)),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  objectiveEarnedScore.toStringAsFixed(1),
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                    fontSize: ResponsiveUtil.isTablet(context) ? 48 : 40,
                    fontWeight: FontWeight.bold,
                    color: Colors.blue.shade700,
                  ),
                ),
                Text(
                  ' / ${objectiveTotalScore.toStringAsFixed(1)}',
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                    fontSize: ResponsiveUtil.isTablet(context) ? 26 : 22,
                    fontWeight: FontWeight.bold,
                    color: Colors.grey.shade600,
                  ),
                ),
              ],
            ),
              ],
            ),
      ),
    );
  }

  Widget _buildInfoBox({required String label, required String value, required IconData icon}) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    final double standardSpacing = ResponsiveUtil.getSpacing(context, 16.0);
    
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
            Row(
              children: [
              Icon(icon, color: Colors.blue.shade800, size: ResponsiveUtil.getIconSize(context)),
              SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                Text(
                label,
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                  fontSize: ResponsiveUtil.isTablet(context) ? 20 : 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          SizedBox(height: ResponsiveUtil.scaleHeight(context, 4)),
          Text(
            value,
                        style: ResponsiveUtil.getBalancedTextStyle(
                          context,
              fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
              color: Colors.grey.shade700,
                      ),
                    ),
                  ],
      ),
    );
  }
} 